%main = getElement(piece,main,pos)
%   This function retrieves the element letter code as found in the
%   periodic table of elements and it's atomic number and stores those
%   respectively in the fields 'atom' and 'atomnum' while also flagging the
%   elements type to 'atom' in the field 'type'. In case of a lower case
%   letter for nitrogen, oxygen, carbon, sulphur or phosphor, it also sets
%   the boolean in the field 'aromatic' to true.

function [main] = getElement(piece,main,pos)
%% Predefining and loading
%Loading the cell symbol.
load('.\Core\temp\symbol.mat')
%InDss = loadIndices;

%% Some unelegant old code
%{
%The following forloop checks for atoms that are possibly aromatic atoms.
for k = [6 7 8]
    if strcmp(piece,symbol(k))
        Z = k;
        element = symbol{k};
        type = 'atom';
        return %Return to make sure the lines after the forloop aren't run.
               %Also to make the loop run faster, since it now terminates
               %as soon as it has found the needed atom.
    elseif strcmp(piece,lower(symbol(k)))
        Z = k;
        aromat = 1;find
        element = symbol{k};
        type = 'atom';
        return %Same here as return above.
    else
    end
end
%}

%% The more elegant code
%The following check which atom number corrosponds with the inputted string
%named 'piece'. The cell 'symbol' contains all "known" 118 elements and an
%asterisk.
Z = find(ismember(symbol,piece),1);

%This if statement check whether the element has been found and whether or
%not it is possibly an aromatic atom or an invalid sign for a SMILES atom.
if isempty(Z) && ~isempty(find(ismember(symbol,upper(piece)),1))
    %This should only happen if 'piece' contains a lower-case 
    %letter and the atom therefore is aromatic.
    Z = find(ismember(symbol,upper(piece)));
    if Z >= 6 && Z <=8 || Z == 15 || Z == 16  %To make ABSOLUTELY sure 
        %it should be aromatic.
        aromat = true;
    else
        error(['Non aromatic lower-case letter entered the aromatic' ...
            ' check. This should not be possible within SMILES rules.' ... 
            ' Entered string: ' piece])
    end
elseif isempty(find(ismember(symbol,upper(piece)),1)) && isempty(Z)
    error(['The inputted lower-case string is not a known existing '...
        'element. This string was: ' piece])
else
    %For when the corrosponding atom number had already been found and the 
    %atom therefore is not aromatic.
    aromat = false;
end
%Preparing output elements 'element' and 'type'. This returns a correctly
%capitalised letter code aromatic single letter lower-case inputs.
main(pos).element = symbol{Z};
main(pos).type = 'atom';
main(pos).atomnum = Z;
main(pos).aromatic = aromat;
%% End
end